package com.exchange.service;

import com.exchange.entity.Order;
import com.exchange.entity.Product;
import com.exchange.repository.OrderRepository;
import com.exchange.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AnalyticsService {
    
    @Autowired
    private OrderRepository orderRepository;
    
    @Autowired
    private ProductRepository productRepository;
    
    public Map<String, Object> getMerchantDashboard(Long merchantId) {
        Map<String, Object> dashboardData = new HashMap<>();
        
        // Get current month
        LocalDateTime startOfMonth = LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth());
        
        // Order statistics
        long totalOrders = orderRepository.countByMerchantId(merchantId);
        long currentMonthOrders = orderRepository.countByMerchantIdAndMonth(merchantId, startOfMonth);
        
        // Calculate orders by status
        List<Order> pendingOrders = orderRepository.findByMerchantIdAndOrderStatus(merchantId, Order.OrderStatus.PENDING);
        List<Order> processingOrders = orderRepository.findByMerchantIdAndOrderStatus(merchantId, Order.OrderStatus.PROCESSING);
        List<Order> shippedOrders = orderRepository.findByMerchantIdAndOrderStatus(merchantId, Order.OrderStatus.SHIPPED);
        List<Order> deliveredOrders = orderRepository.findByMerchantIdAndOrderStatus(merchantId, Order.OrderStatus.DELIVERED);
        List<Order> cancelledOrders = orderRepository.findByMerchantIdAndOrderStatus(merchantId, Order.OrderStatus.CANCELLED);
        
        // Product statistics
        Long totalProducts = productRepository.countByMerchantId(merchantId);
        List<Product> products = productRepository.findByMerchantId(merchantId);
        Long activeProducts = products.stream()
                .filter(p -> p.getStatus() == Product.ProductStatus.ACTIVE)
                .count();
        
        // Prepare the response
        dashboardData.put("totalOrders", totalOrders);
        dashboardData.put("currentMonthOrders", currentMonthOrders);
        dashboardData.put("orderStatusBreakdown", Map.of(
            "pending", (long) pendingOrders.size(),
            "processing", (long) processingOrders.size(),
            "shipped", (long) shippedOrders.size(),
            "delivered", (long) deliveredOrders.size(),
            "cancelled", (long) cancelledOrders.size()
        ));
        dashboardData.put("totalProducts", totalProducts);
        dashboardData.put("activeProducts", activeProducts);
        
        return dashboardData;
    }
    
    public Map<String, Object> getOrderAnalytics(Long merchantId) {
        Map<String, Object> analytics = new HashMap<>();
        
        // Get orders for the merchant
        List<Order> orders = orderRepository.findByMerchantId(merchantId);
        
        // Calculate various metrics
        Map<String, Long> statusCount = new HashMap<>();
        for (Order order : orders) {
            String status = order.getOrderStatus().toString();
            statusCount.put(status, statusCount.getOrDefault(status, 0L) + 1);
        }
        
        analytics.put("totalOrders", (long) orders.size());
        analytics.put("statusDistribution", statusCount);
        
        // Add other analytics as needed
        analytics.put("ordersByDeliveryType", calculateOrdersByDeliveryType(orders));
        
        return analytics;
    }
    
    private Map<String, Long> calculateOrdersByDeliveryType(List<Order> orders) {
        Map<String, Long> deliveryTypeCount = new HashMap<>();
        
        for (Order order : orders) {
            String deliveryType = order.getDeliveryType().toString();
            deliveryTypeCount.put(deliveryType, deliveryTypeCount.getOrDefault(deliveryType, 0L) + 1);
        }
        
        return deliveryTypeCount;
    }
}